package com.caiyi.financial.nirvana.sms.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.caiyi.financial.nirvana.sms.entity.SmsPhoneFile;
import com.caiyi.financial.nirvana.sms.entity.SmsUser;
import com.caiyi.financial.nirvana.sms.entity.SmsUserSign;
import com.caiyi.financial.nirvana.sms.enums.ReturnCodeEnum;
import com.caiyi.financial.nirvana.sms.enums.SmsGatewayTypeEnum;
import com.caiyi.financial.nirvana.sms.enums.SmsMsgOperatorEnum;
import com.caiyi.financial.nirvana.sms.enums.SmsUserSignStatusEnum;
import com.caiyi.financial.nirvana.sms.jedis.JedisKey;
import com.caiyi.financial.nirvana.sms.jedis.JedisService;
import com.caiyi.financial.nirvana.sms.mapper.SmsPhoneFileMapper;
import com.caiyi.financial.nirvana.sms.mapper.SmsSignMapper;
import com.caiyi.financial.nirvana.sms.querybean.CountPhoneQueryBean;
import com.caiyi.financial.nirvana.sms.querybean.MsgSendParamsQueryBean;
import com.caiyi.financial.nirvana.sms.querybean.SignQueryBean;
import com.caiyi.financial.nirvana.sms.util.CommUtil;
import com.caiyi.financial.nirvana.sms.util.HttpClientUtil;
import com.caiyi.financial.nirvana.sms.util.SignUtil;
import com.youyu.common.api.Result;
import com.youyu.common.enums.BaseResultCode;
import com.youyu.common.utils.YyAssert;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class MsgSendService {

    @Value("${spring.profiles.active}")
    private String env;

    @Value("${customer.batch.num}")
    private int batchNum;

    private static Logger logger = LoggerFactory.getLogger(MsgSendService.class);
    @Autowired
    private SmsSignMapper smsSignMapper;
    @Autowired
    private SmsPhoneFileMapper smsPhoneFileMapper;

    public JSONObject sendMessage(MsgSendParamsQueryBean msgSendParamsQueryBean) {
        if (StringUtils.isNotEmpty(msgSendParamsQueryBean.getPhoneTypes())) {
            StringBuffer sbPhone = new StringBuffer();
            SmsPhoneFile phoneFile = smsPhoneFileMapper.getSmsPhoneFile(msgSendParamsQueryBean.getId());
            String[] phoneTypeArr = msgSendParamsQueryBean.getPhoneTypes().split(",");
            for (String phoneType : phoneTypeArr) {
                if (phoneType.equals(String.valueOf(SmsGatewayTypeEnum.YD.index))) {
                    sbPhone.append(phoneFile.getYdPhones()).append(",");
                }
                if (phoneType.equals(String.valueOf(SmsGatewayTypeEnum.LT.index))) {
                    sbPhone.append(phoneFile.getLtPhones()).append(",");
                }
                if (phoneType.equals(String.valueOf(SmsGatewayTypeEnum.DX.index))) {
                    sbPhone.append(phoneFile.getDxPhones()).append(",");
                }
            }
            msgSendParamsQueryBean.setPhones(sbPhone.deleteCharAt(sbPhone.length() - 1).toString());
        }

        YyAssert.isFalse(StringUtils.isBlank(msgSendParamsQueryBean.getPhones()), ReturnCodeEnum.PARAMS_ERROR.code, "手机号不能为空！");
        YyAssert.isFalse(StringUtils.isBlank(msgSendParamsQueryBean.getContent()), ReturnCodeEnum.PARAMS_ERROR.code, "短信内容不能为空！");
        String msgContent = msgSendParamsQueryBean.getContent();
        YyAssert.isFalse(msgContent.startsWith("【") || msgContent.endsWith("】"), ReturnCodeEnum.PARAMS_ERROR.code, "内容格式不正确！");

        if (msgSendParamsQueryBean.getSignType() == 1) {
            msgContent = msgSendParamsQueryBean.getSign() + msgContent;
        } else {
            msgContent = msgContent + msgSendParamsQueryBean.getSign();
        }

        String phones = msgSendParamsQueryBean.getPhones();
        Map<String, String> params = new HashMap();
        params.put("account", msgSendParamsQueryBean.getAccount());
        params.put("content", msgContent);
        //获取用户信息
        String key = String.format(JedisKey.SMS_USER, msgSendParamsQueryBean.getAccount());
        String userJson = JedisService.get(key);
        SmsUser user = JSON.parseObject(userJson, SmsUser.class);
        String uri = CommUtil.getSendUrl(env);
        int num = 11 * batchNum + batchNum;
        String content = "";
        if (StringUtils.isNotEmpty(phones)) {
            int number = (phones.length() % num == 0) ? (phones.length() / num) : (phones.length() / num) + 1;
            for (int i = 0; i < number; i++) {
                int beginIndex = i * num;
                int endIndex = (i + 1) * num;
                if (i == number - 1) {
                    endIndex = phones.length();
                }
                String sendPhones = phones.substring(beginIndex, endIndex);
                params.put("phones", sendPhones);
                //生成签名
                params.remove("sign");
                params.put("sign", SignUtil.createSign(params, user.getPassword()));
                content = HttpClientUtil.doPost(uri, JSON.toJSONString(params));
                logger.info("return : {}, requestUrl : {}", content, uri);
                if (null != content) {
                    Result res = JSONObject.parseObject(content, Result.class);
                    if (!res.code.equals(ReturnCodeEnum.SUCCESS.getCode())) {
                        return JSONObject.parseObject(content);
                    }
                }
            }
        }
        return JSONObject.parseObject(content);
    }


    public CountPhoneQueryBean importPhone(Set<String> setPhones) {
        int yiDong = 0;
        int lianTong = 0;
        int dianXin = 0;
        int count = setPhones.size();
        int unknownCount = 0;
        //StringBuilder phoneBuilder = new StringBuilder();
        StringBuilder ydPhones = new StringBuilder();
        StringBuilder ltPhones = new StringBuilder();
        StringBuilder dxPhones = new StringBuilder();
        for (String phone : setPhones) {
            int operator = CommUtil.getPhoneOperator(phone);
            if (operator == SmsMsgOperatorEnum.YD.index) {
                //phoneBuilder.append(phone + ",");
                ydPhones.append(phone + ",");
                yiDong++;
                continue;
            }
            if (operator == SmsMsgOperatorEnum.LT.index) {
                // phoneBuilder.append(phone + ",");
                ltPhones.append(phone + ",");
                lianTong++;
                continue;
            }
            if (operator == SmsMsgOperatorEnum.DX.index) {
                //phoneBuilder.append(phone + ",");
                dxPhones.append(phone + ",");
                dianXin++;
                continue;
            }
            unknownCount = unknownCount + 1;
        }
//        if (StringUtils.isNotBlank(phoneBuilder.toString())) {
//            phoneBuilder = phoneBuilder.deleteCharAt(phoneBuilder.length() - 1);
//        }
        if (StringUtils.isNotBlank(ydPhones.toString())) {
            ydPhones = ydPhones.deleteCharAt(ydPhones.length() - 1);
        }
        if (StringUtils.isNotBlank(ltPhones.toString())) {
            ltPhones = ltPhones.deleteCharAt(ltPhones.length() - 1);
        }
        if (StringUtils.isNotBlank(dxPhones.toString())) {
            dxPhones = dxPhones.deleteCharAt(dxPhones.length() - 1);
        }
        SmsPhoneFile phoneFile = new SmsPhoneFile();
        phoneFile.setDxPhones(dxPhones.toString());
        phoneFile.setLtPhones(ltPhones.toString());
        phoneFile.setYdPhones(ydPhones.toString());
        smsPhoneFileMapper.insert(phoneFile);
        return new CountPhoneQueryBean(yiDong, lianTong, dianXin, count, unknownCount, phoneFile.getId());
    }

    /**
     * 获取用户签名
     *
     * @param account
     * @return
     */
    public List<SmsUserSign> getSign(String account) {
        List<SmsUserSign> list = new ArrayList<>();
        try {
            SignQueryBean signQueryBean = new SignQueryBean();
            signQueryBean.setAccount(account);
            signQueryBean.setStatus(SmsUserSignStatusEnum.PASS.index);
            list = smsSignMapper.selectUserSignListByParams(signQueryBean);
        } catch (Exception e) {
            logger.error("get getSign by account error....", e);
            YyAssert.isFalse(true, BaseResultCode.SYSTEM_ERROR);
        }
        return list;
    }
}
